UseController   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 43
dl 0
loc 60
rs 10
c 0
b 0
f 0
wmc 7

2 Functions

Rating   Name   Duplication   Size   Complexity  
A execute 0 9 2
B switchPhpVersionTo 0 38 5
1
import OS from '../client/OS'
2
import {error, info, success, warning} from '../utils/console'
3
import {getLinkedPhpVersion, getPhpFpmByName, supportedPhpVersions} from '../utils/phpFpm'
4
5
class UseController {
6
7
    /**
8
     * Switch the service to the given version.
9
     */
10
    execute = async (service: string, version: string): Promise<boolean> => {
11
        switch (service) {
12
        case 'php':
13
            info(`Switching to PHP ${version}...`)
14
            await this.switchPhpVersionTo(version)
15
            return true
16
        default:
17
            error('Invalid service.')
18
            return false
19
        }
20
    }
21
22
    /**
23
     * Switch the active PHP version to the provided phpVersion string.
24
     * @param phpVersion
25
     */
26
    switchPhpVersionTo = async (phpVersion: string): Promise<void> => {
27
        const currentPhpVersion = await getLinkedPhpVersion()
28
29
        if (!supportedPhpVersions.includes(phpVersion)) {
30
            throw Error(`Invalid PHP version. Please pick one of the following version: ${supportedPhpVersions.join(', ')}`)
31
        }
32
33
        if (currentPhpVersion.versionName === phpVersion) {
34
            warning(`PHP ${phpVersion} is already active.`)
35
            return
36
        }
37
38
        const newPhpVersion = getPhpFpmByName(`php@${phpVersion}`)
39
40
        if (newPhpVersion.isEndOfLife) {
41
            warning('This PHP version is End Of Life. Be aware it might contain security flaws.\n   Please check http://php.net/supported-versions.php for more information.')
42
        }
43
44
        // Make sure the PHP version is installed.
45
        const isVersionInstalled = await OS.getInstance().packageManager.packageIsInstalled(newPhpVersion.service)
46
47
        if (!isVersionInstalled) {
48
            info(`PHP ${newPhpVersion.versionName} not found, installing now...`)
49
            await OS.getInstance().packageManager.install(newPhpVersion.service, false)
50
            info(`Configuring PHP ${newPhpVersion.versionName}...`)
51
            await newPhpVersion.configure()
52
        }
53
54
        await currentPhpVersion.unLinkPhpVersion()
55
56
        // TODO: Relink some libs like libjpeg etc.
57
58
        await newPhpVersion.linkPhpVersion()
59
60
        await currentPhpVersion.stop()
61
        await newPhpVersion.start()
62
63
        success(`Successfully switched to PHP ${newPhpVersion.versionName}.`)
64
    }
65
66
}
67
68
export default UseController
69